package com.ydlclass.netty;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author Knife
 */
public class MyCompletableFuture {
    public static void main(String[] args) {
        /**
         * CompletableFuture可以获取子线程的结果，并可以在主线程中阻塞等待其完成
         */
        CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
        new Thread(()->{
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 8;
            completableFuture.complete(i);
        }).start();

        try {
            // get方法是一个阻塞方法, 也可以进行设置时间进行等待，在规定时间内等不到就抛出异常
            System.out.println(completableFuture.get(1, TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
